<template>
  <div id="bannerManage">
    <!-- 搜索框-->
    <banner-search
      :show-search="showSearch"
      @handle-query="handleQuery($event)"
      @handle-reset="handleQuery({}, true)"
    ></banner-search>
    <!-- 列表 -->
    <el-card shadow="never">
      <!-- 表格工具栏 -->
      <div class="toolbar">
        <!-- 左侧工具栏 -->
        <div>
          <el-button :icon="Plus" type="success" @click="openAddModel">
            新增
          </el-button>
          <el-button
            :disabled="removeIdList.length === 0"
            :icon="Delete"
            type="danger"
            @click="handleBatchDel"
          >
            删除
          </el-button>
        </div>
        <!-- 右侧工具栏 -->
        <div>
          <el-button
            :icon="Refresh"
            circle
            title="刷新"
            @click="handleQuery({}, true)"
          />
          <el-popover placement="bottom" trigger="click">
            <template #reference>
              <el-button :icon="Operation" circle title="筛选列" />
            </template>
            <el-scrollbar max-height="350px">
              <template v-for="col in cols" :key="col.props">
                <el-checkbox v-model="col.show" :label="col.label" />
              </template>
            </el-scrollbar>
          </el-popover>
          <el-button
            :icon="Search"
            circle
            title="搜索"
            @click="handleSearchShow"
          ></el-button>
        </div>
      </div>
      <!-- 列表 -->
      <el-table
        :data="tableData"
        border
        highlight-current-row
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="50"
        ></el-table-column>
        <el-table-column
          v-if="handleColShow('id')"
          align="center"
          label="数据Id"
          prop="id"
          show-overflow-tooltip
          width="150"
        ></el-table-column>
        <el-table-column
          v-if="handleColShow('image')"
          align="center"
          label="图片"
          prop="image"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-image
              :preview-src-list="[scope.row.image]"
              :src="scope.row.image"
              preview-teleported
              style="width: 50px"
            ></el-image>
            <!--:src="BASE_IMAGE_URL + scope.row.image"-->
            <!--:preview-src-list="[BASE_IMAGE_URL + scope.row.image]"-->
          </template>
        </el-table-column>
        <el-table-column
          v-if="handleColShow('toPath')"
          align="center"
          label="跳转路径"
          prop="toPath"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          v-if="handleColShow('areaNum')"
          align="center"
          label="所属区域"
          prop="areaNum"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{ getAreaLabel(scope.row.areaNum) }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="handleColShow('isInner')"
          align="center"
          label="是否是路由"
          prop="isInner"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{ scope.row.isInner ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="handleColShow('status')"
          align="center"
          label="状态"
          prop="status"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            <el-popconfirm
              :icon="InfoFilled"
              cancel-button-text="取消"
              confirm-button-text="确定"
              icon-color="#626AEF"
              title="确定要修改当前状态?"
              width="220"
              @confirm="switchStatus(scope.row)"
            >
              <template #reference>
                <el-switch
                  :model-value="scope.row.status == 1"
                  active-text="正常"
                  class="ml-2"
                  inactive-text="禁用"
                  inline-prompt
                  style="
                    --el-switch-on-color: #13ce66;
                    --el-switch-off-color: #ff4949;
                  "
                />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <el-table-column
          v-if="handleColShow('createTime')"
          align="center"
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
          width="200"
        ></el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              content="编辑"
              effect="dark"
              placement="bottom"
            >
              <el-button
                :icon="Edit"
                circle
                size="small"
                type="primary"
                @click="handleEditShow(scope.row)"
              />
            </el-tooltip>
            <el-tooltip
              class="box-item"
              content="删除"
              effect="dark"
              placement="bottom"
            >
              <el-button
                :icon="Delete"
                circle
                size="small"
                type="danger"
                @click="handleDel(scope.row.id)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-scrollbar>
        <div class="pagination">
          <el-pagination
            :page-size="queryData.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="parseInt(total)"
            background
            layout="prev,pager,next,jumper,total,sizes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-scrollbar>
    </el-card>

    <!-- 新增弹窗-->
    <el-dialog
      v-model="addVisible"
      center
      destroy-on-close
      title="轮播图新增"
      width="40%"
      @close="handleAddClose"
    >
      <!-- 滚动 -->
      <el-scrollbar max-height="60vh">
        <!-- 表单 -->
        <el-form
          ref="addFormRef"
          :model="addFormData"
          :rules="rules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="路径" prop="toPath">
                <el-input
                  v-model="addFormData.toPath"
                  :max="255"
                  placeholder="请输入跳转路径"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="是否是路由" prop="isInner">
                <el-radio-group v-model="addFormData.isInner">
                  <el-radio :value="1" label="是" />
                  <el-radio :value="0" label="否" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="图片" prop="image">
                <upload-image
                  ref="uploadImage"
                  :urls="[addFormData.image]"
                  @update:url="handleUpdateUrl($event, true)"
                ></upload-image>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="所属区域" prop="areaNum">
                <el-radio-group v-model="addFormData.areaNum">
                  <el-radio
                    v-for="item in AreaType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button type="primary" @click="handleAddSubmit">确 定</el-button>
          <el-button @click="handleAddClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑轮播图弹窗-->
    <el-drawer
      v-model="editVisible"
      :before-close="handleEditClose"
      destroy-on-close
      direction="rtl"
      size="40%"
    >
      <template #header="{ titleClass }">
        <div
          :class="titleClass"
          style="text-align: center; font-size: 20px; font-weight: bold"
        >
          轮播图编辑
        </div>
      </template>
      <!-- 滚动 -->
      <el-scrollbar max-height="60vh">
        <!-- 表单 -->
        <el-form
          ref="editFormRef"
          :model="selectData"
          :rules="rules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="路径" prop="toPath">
                <el-input
                  v-model="selectData.toPath"
                  :max="255"
                  placeholder="请输入跳转路径"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="是否是路由" prop="isInner">
                <el-radio-group v-model="selectData.isInner">
                  <el-radio :value="1" label="是" />
                  <el-radio :value="0" label="否" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="图片" prop="image">
                <upload-image
                  ref="uploadImage"
                  :urls="[selectData.image]"
                  @update:url="handleUpdateUrl($event)"
                ></upload-image>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="所属区域" prop="areaNum">
                <el-radio-group v-model="selectData.areaNum">
                  <el-radio
                    v-for="item in AreaType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button type="primary" @click="handleEditSumbit">确 定</el-button>
          <el-button @click="handleEditClose">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import {
  Delete,
  Edit,
  InfoFilled,
  Operation,
  Plus,
  Refresh,
  Search,
} from "@element-plus/icons-vue";
import { ref } from "vue";
import {
  BannerControllerService,
  BannerInsertDTO,
  BannerQueryParams,
  BannerVO,
} from "@/api";

import { ElMessage, ElMessageBox } from "element-plus";
import BannerSearch from "@/views/back/system/banner/components/BannerSearch.vue";
import UploadImage from "@/components/UploadImage.vue";
import AreaType from "@/types/AreaType";

/**
 * 查询搜索开始
 */
const queryInit = {
  pageNum: 1,
  pageSize: 10,
  beginTime: "",
  endTime: "",
  keyword: "",
};
//查询数据对象
const queryData = ref({ ...queryInit });

//查询事件
function handleQuery(query: BannerQueryParams, reset?: boolean) {
  //处理时间函数
  if (query?.createTime) {
    queryData.value.beginTime = query.createTime[0];
    queryData.value.endTime = query.createTime[1];
  }
  if (query?.keyword) {
    queryData.value.keyword = query.keyword;
  }
  //重置页码
  if (reset) {
    queryData.value = { ...queryInit };
  }
  let data = queryData.value;
  BannerControllerService.queryBannerPageUsingGet(
    data.pageNum,
    data.pageSize,
    data.beginTime,
    data.endTime,
    data.keyword
  ).then((res) => {
    const { data } = res;
    total.value = data?.total || 0;
    tableData.value = data?.rows || [];
  });
}

//获取所属区域的描述
function getAreaLabel(value: number) {
  return AreaType[value - 1].label;
}

// 页面创建时调用
handleQuery({});
//查询的数据
const total = ref<number>(0); //总条数
const tableData = ref<BannerVO[]>([]); // 数据集合

//页面显示条数变化
function handleSizeChange(value: number) {
  queryData.value.pageSize = value;
  handleQuery({});
}

//页码变化
function handleCurrentChange(value: number) {
  queryData.value.pageNum = value;
  handleQuery({});
}

/**
 * 查询数据结束
 */

const rules = {
  toPath: [{ required: true, message: "请输入路径", trigger: "change" }],
  image: [{ required: true, message: "请上传图片", trigger: "blur" }],
}; // 表单规则

/**
 * 工具栏开始
 *
 */
// 1、新增开始
const init = {
  /**
   * 所属区域数字
   */
  areaNum: 1,
  /**
   * 轮播图图片链接
   */
  image: "",
  /**
   * 是否是内部链接
   */
  isInner: 1,
  /**
   * 跳转路径
   */
  toPath: "",
};
const addVisible = ref(false); //新增弹窗显示
const addFormData = ref<BannerInsertDTO>({ ...init }); //添加表单数据
const addFormRef = ref(); //新增表单对象
// 打开弹窗
function openAddModel() {
  addFormData.value = { ...init };
  addVisible.value = true;
}

//关闭弹窗事件
function handleAddClose() {
  if (addVisible.value) {
    ElMessageBox.confirm("确定要关闭弹窗吗？")
      .then(() => {
        addVisible.value = false;
      })
      .catch(() => {
        ElMessage.info("取消了关闭弹窗");
      });
  }
}

//获取图片的值
function handleUpdateUrl(list: string[], addFlag?: boolean) {
  if (list.length > 0) {
    if (addFlag === true) {
      addFormData.value.image = list[0];
    } else {
      selectData.value.image = list[0];
    }
  }
}

//新增提交事件
async function handleAddSubmit() {
  console.log(addFormRef.value);
  //校验
  await addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      BannerControllerService.insertBannerUsingPost(addFormData.value).then(
        (res) => {
          handleQuery({}, true);
          ElMessage.success(res.data);
          addVisible.value = false;
        }
      );
    }
  });
}

// 1、新增结束
// 2、批量删除开始
const selectionList = ref<Array<BannerVO>>(); //选中的数据集合
const removeIdList = ref<number[]>([]); //选中的数据Id集合
function handleSelectionChange(value: BannerVO[]) {
  selectionList.value = value;
  //获取选中的数据id
  removeIdList.value = value.map((item) => item.id!);
}

//批量删除事件
function handleBatchDel() {
  ElMessageBox.confirm(
    "确定要删除选中的" + removeIdList.value?.length + "条数据吗？",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      BannerControllerService.delBannerUsingDelete(removeIdList.value).then(
        (res) => {
          ElMessage.success(res.data);
          handleQuery({}, true);
        }
      );
    })
    .catch(() => {
      ElMessage.info("取消删除！");
    });
}

// 2、批量删除结束
// 6、筛选列开始
//列数据
const cols = ref([
  {
    label: "数据Id",
    props: "id",
    show: false,
  },
  {
    label: "图片",
    props: "image",
    show: true,
  },
  {
    label: "路径",
    props: "toPath",
    show: true,
  },
  {
    label: "所属区域",
    props: "areaNum",
    show: true,
  },
  {
    label: "是否路由",
    props: "isInner",
    show: true,
  },
  {
    label: "状态",
    props: "status",
    show: true,
  },
  {
    label: "创建时间",
    props: "createTime",
    show: true,
  },
]);

//列展示处理
function handleColShow(prop: string) {
  return cols.value.filter((col) => col.props === prop)[0].show;
}

// 6、筛选列结束
// 7、搜索展示开始
//搜索展示处理
const showSearch = ref(true);

function handleSearchShow() {
  showSearch.value = !showSearch.value;
}

// 7、搜索展示结束
/**
 * 工具栏结束
 * 表格操作开始
 */

// 1、修改轮播图状态开始
const switchStatus = (row: any) => {
  const status = row.status === 1 ? 0 : 1;
  BannerControllerService.updateBannerStaticUsingPut({
    id: row.id,
    status: status,
  }).then((res) => {
    ElMessage.success(res.data);
    handleQuery({}, true);
  });
};
// 1、修改轮播图状态结束
// 选中的数据
const selectData = ref<BannerVO>({});

// 3、编辑轮播图内容开始
const editVisible = ref(false); //编辑弹窗显示标志
const editFormRef = ref(); //编辑表单对象
// 打开展示弹窗
function handleEditShow(row: BannerVO) {
  console.log(row);
  selectData.value = { ...row };
  editVisible.value = true;
  console.log(selectData.value);
}

//关闭展示弹窗
function handleEditClose() {
  ElMessageBox.confirm("确定要关闭吗？")
    .then(() => {
      editVisible.value = false;
    })
    .catch(() => {
      // catch error
    });
}

function handleEditSumbit() {
  editFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      BannerControllerService.updateBannerUsingPut(selectData.value).then(
        (res) => {
          handleQuery({}, true);
          ElMessage.success(res.data);
          editVisible.value = false;
        }
      );
    }
  });
}

// 3、编辑轮播图内容结束
// 4、删除一条轮播图数据

const handleDel = (id: number) => {
  if (!id) {
    ElMessage.warning("请选择数据后再删除！");
    return;
  }
  //删除数据
  BannerControllerService.delBannerUsingDelete([id]).then((res) => {
    ElMessage.success(res.data);
    handleQuery({}, true);
  });
};
// const BASE_IMAGE_URL = inject("BASE_IMAGE_URL");
</script>

<style lang="scss" scoped>
#bannerManage {
  .toolbar {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .pagination {
    margin-top: 12px;
  }
}
</style>
